<template>
    <el-tabs type="border-card" v-model="activeTabTitle" :activate-name="activeTabTitle" @tab-click="handleTabClick">
        <el-tab-pane v-for="item in tabs" :label='$t("range.tab_type." + item.value)' :key="item.value" :name="item.title">
            <div class="app-container">
                <!-- <el-alert :title="alert.title" v-if="alert.dynamicVariant == 'success' ? true : false" :type="alert.dynamicVariant" :description="alert.successMessage" @dismissed="dismissCountDown=0" @dismiss-count-down="countDownChanged" fade-transition show-icon></el-alert> -->
                <br>
                <el-row type="flex" class="row-bg btn-row" justify="end">
                    <el-button class="filter-item" size="mini" type="primary" @click="showModal(null, 'Add')" icon="el-icon-plus">{{$t('range.add')}}</el-button>
                </el-row>
                <el-row type="flex">
                    <el-form :inline="true" class="demo-form-inline query" label-position="left" size="small" >
                        <el-form-item :label='$t("range.cards") + ":"'>
                            <el-select v-model="q.card_code" :placeholder='$t("range.all")'>
                            <el-option :label='$t("range.all")' :value=null></el-option>
                            <el-option v-for="c of cards" :key="c.value" :label="c.value" :value="c.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label='$t("range.range_code") + ":"'>
                            <el-select v-model="q.range_code" :placeholder='$t("range.all")'>
                            <el-option :label='$t("range.all")' :value=null></el-option>
                            <el-option v-for="r of rangeCode" :key="r.key" :label="r.value" :value="r.value"></el-option>
                            </el-select>
                        </el-form-item> 
                
                        <el-button class="filter-item" size="mini" type="primary" @click="search">{{$t('range.search')}}</el-button>
                        <el-button class="filter-item" size="mini" type="primary" @click="reset">{{$t('range.reset')}}</el-button>
                       
                    </el-form>
                </el-row>
                <el-row>
                    <el-table :data="rangeData.list" stripe border fit highlight-current-row>
                        <el-table-column prop="range_code" :label='$t("range.range_code")' sortable width="190"></el-table-column>
                        <el-table-column prop="range_from_to" :label='$t("range.range")' sortable width="150" align="center"></el-table-column>
                        <el-table-column prop="cards" :label='$t("range.cards")' sortable min-width="500" align="center"></el-table-column>
                        <el-table-column prop="companies" :label='$t("range.companies")' sortable width="150" align="center"></el-table-column>
                        <el-table-column prop="range_status" :label='$t("range.status")' width="125" align="center">
                            <template slot-scope="scope">
                                <el-alert class="el-badge_status" :title="changeTitleStatus(scope.row)" center :type="(scope.row.range_status === 'Active' ? 'success' : 'error')" :closable="false"></el-alert>
                            </template>
                        </el-table-column>
                        <el-table-column prop="updated_at" :label='$t("range.update_at")' sortable width="200"></el-table-column>
                        <el-table-column :label='$t("range.action")' width="400" fixed="right" align="center">
                            <template slot-scope="scope">
                            <div>
                                <el-button class="filter-item" size="mini" type="primary" @click="showModal(scope.row, 'View')">{{$t('range.view')}}</el-button>
                                <el-button class="filter-item" size="mini" :type="changeColorType(scope.row)" @click="showModal(scope.row, 'Status')">{{changeAction(scope.row)}}</el-button>
                                <el-button class="filter-item" size="mini" type="danger" :name="button.Edit" @click="showModal(scope.row, 'Edit')">{{$t('range.edit')}}</el-button>
                                <el-button class="filter-item" size="mini" type="warning" @click="showModal(scope.row, 'Assign')">{{$t('range.assign')}}</el-button>
                            </div>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination">
                        <el-pagination  @size-change="handleSizeChange" 
                                        @current-change="handleCurrentChange"
                                        :current-page="q.$page" 
                                        :page-sizes="$store.state.app.pageSizeArr"
                                        :page-size="q.$size"
                                        layout="total, sizes, prev, pager, next, jumper"
                                        :total="rangeData.total_count">
                        </el-pagination>
                    </div>
                </el-row>

                <add-range v-if="showAdd" :showAdd.sync="showAdd" :details="details" @ok="submit"></add-range>
                <edit-range v-if="showEdit" :showEdit.sync="showEdit" :details="details" @ok="submit"></edit-range>
                <status-range v-if="showStatus" :showStatus.sync="showStatus" :details="details" @ok="submit"></status-range>
                <assign-range v-if="showAssign" :showAssign.sync="showAssign" :details="details" @ok="submit"></assign-range>
            </div>
        </el-tab-pane>
    </el-tabs>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import addRange from './addRange'
import editRange from './editRange'
import statusRange from './statusRange'
import assignRange from './assignRange'
import { encodeQueryData } from '@/utils/patch'
import { findstrict } from '@/utils/helper'

export default {
    components: { addRange, editRange, statusRange, assignRange },
    name: 'range',
    data: () => {
        return {
            cardData: [],
            rangeData: {},
            orderData: {},
            template: {
                caption: 'Range'
            },
            striped: true,
            button: {
                add: 'Add',
                edit: 'Edit',
                enable: 'Enable',
                assign: 'Assign',
                view: 'View',
                search: 'Search',
                reset: 'Reset'
            },
            option: {
                cards: '',
                rangecode: ''
            },
            params: {
                pagesize: 5,
                page: 1,
                where: {
                    cards: '',
                    rangeCode: '',
                    type: 0
                }
            },
            details: {
                default: false,
                show: false,
                title: '',
                action: '',
                disabled: false,
                endButton: '',
                type_color: '',
                range: {
                    id: 0,
                    range_code: '',
                    range_from: '',
                    range_to: '',
                    status: '',
                    range_status: '',
                    type: '',
                    range_type: ''
                },
                assignRange: {},
                company: {
                    assign: '',
                    list: {}
                },
                card_list: [],
                data_range: {}
            },
            showAdd: false,
            showEdit: false,
            showStatus: false,
            showAssign: false,
            tabs: [{
                title: 'Collection',
                value: '0'
            }, {
                title: 'Payment',
                value: '1'
            }],
            activeTabTitle: 'Collection',
            activeTab: 0,
            alert: {
                title: '',
                dismissCountDown: 0,
                dynamicVariant: '',
                successMessage: ''
            },
            q: {$size: 30, $page: 1},
            queryParam: ''
        }
    },
    methods: {
        ...mapActions('common', {
            getCards: 'getCards',
            getRangeCode: 'getRangeCode',
            getCompanies: 'getCompanies',
            getOrderDeposit: 'getOrderDeposit',
            getOrderWithdraw: 'getOrderWithdraw'
        }),
        ...mapActions('range', {
            getRangeList: 'getRangeList',
            insertRange: 'insertRange',
            updatetRange: 'updatetRange',
            updatetRangeStatus: 'updatetRangeStatus',
            assignRange: 'assignRange'
        }),
        showModal(range, action) {
            switch(action) {
                case 'Add':
                    this.showAdd = true
                    this.details.action = action
                    this.details.title = this.$t('range.add') + this.$t('range.name')
                    this.details.range.type = this.activeTab
                    this.details.range.range_type = this.activeTabTitle
                break;
                case 'View':
                case 'Edit':
                    this.showEdit = true
                    this.details.title = this.$t('range.add') + this.$t('range.name')
                    this.details.disabled = action === 'View'
                    this.details.action = action
                    this.details.endButton = action === 'Edit' ? 'Cancel' : 'Close'
                    this.details.range.id = range.id
                    this.details.range = range
                break;
                case 'Status':
                    this.showStatus = true
                    this.details.action = action
                    this.details.title = this.$t('range.update_range') + this.$t('range.name')
                    this.details.range = range
                break;
                case 'Assign':

                    this.showAssign = true
                    this.details.action = action
                    this.details.title = this.concat(this.$t('range.assign'), this.$t('range.name'))

                     let item = {};
                    // let cards = [];
                    // let companies = [];
                    let unavailableCards = []
                    
                    let details = this.filterDetails(item, this.rangeData, range.type)

                    details.filterCards.forEach(x => {
                        if(x.cards !== '') {
                            x.cards = x.cards.split(',')
                            x.cards.forEach(c => {
                                if(!unavailableCards.includes(c)) {
                                    unavailableCards.push(c)
                                }
                            })
                        }
                    })

                    let newCards = this.cards.map(card => {
                        let xCard = 'available'
                        let cardAssign = ''
                        let isDisabled = false

                        if(unavailableCards.includes(card)) {
                            xCard = 'unavailable'
                        }

                        if(range.cards) {
                            cardAssign = range.cards.filter(ca => {
                                return ca === card.value
                            })

                            if(cardAssign.length > 0) {
                                this.cardData = [...this.cardData, cardAssign]
                                this.executeOrder(range.type, cardAssign)
                                isDisabled = this.orderData.size > 0
                            }
                        }

                        return {
                            name: xCard,
                            disabled: isDisabled,
                            text: card.value,
                            value: card.value,
                            card: cardAssign,
                            assign: cardAssign.length > 0
                        }
                    })
                this.details.assignRange = newCards
                this.details.company.assign = range.companies
                this.details.company.list = this.companies
                this.details.card_list = range.cards ? range.cards : []
                this.details.data_range = this.rangeData
                this.details.range.type = range.type
                this.details.range = range
                this.getRange()
                break;
            }
        },
        submit(range_data ) {
            let message = ''
            if(range_data !== '' || range_data != null) {
                switch(range_data.action) {
                    case 'Add':
                        this.alert.title = 'Range Notification'                       
                        let range_insert = {
                            range_code: range_data.range_code,
                            range_from: range_data.range_from,
                            range_to: range_data.range_to,
                            status: range_data.status,
                            type: range_data.type,
                            created_by: 'Marvin',
                            updated_by: 'Marvin',
                            param: this.queryParam
                        }
                        
                        this.insertRange(range_insert)
                        message = this.handleComposeMessage('', range_data.action)
                        this.handleNotification(this.alert.title, 'success', message)
                        break
                    case 'Edit':
                        this.alert.title = 'Range Notification'
                        let range_update = {
                            id: range_data.id,
                            range_code: range_data.range_code,
                            range_from: range_data.range_from,
                            range_to: range_data.range_to,
                            status: range_data.status,
                            type: range_data.type,
                            updated_by: 'Marvin',
                            param: this.queryParam
                        }
                        this.updatetRange(range_update)
                        message = this.handleComposeMessage(range_data.range_code, range_data.action)
                        this.handleNotification(this.alert.title, 'success', message)
                        break
                    case 'Status':
                        this.alert.title = 'Range Notification'                       
                        let range_status = {
                            id: range_data.id,
                            status: range_data.status,
                            type: this.activeTab,
                            updated_by: 'Marvin',
                            param: this.queryParam
                        }
                        this.updatetRangeStatus(range_status, this.queryParam)
                        message = this.handleComposeMessage(range_data.range_code, range_data.action) + this.changeStatus(range_data.status)
                        this.handleNotification(this.alert.title, 'success', message)
                        break
                    case 'Assign':
                        this.alert.title = 'Range Notification'
                        let range_assign = Object.assign({
                            id: range_data.id,
                            cards: range_data.cards,
                            companies: range_data.companies,
                            updated_by: 'Marvin',
                            param: this.queryParam
                        })

                        this.assignRange(range_assign)
                        message = this.handleComposeMessage(range_data.range_code, range_data.action)
                        this.handleNotification(this.alert.title, 'success', message)
                        break
                }
            }
        },
        handleComposeMessage(value, flag) {
            let message = ''
            let start = this.$t('range.range_char')
            switch(flag) {
                case 'Add':
                    message = this.$t('range.add_success')
                break
                case 'Edit':
                    message = start.concat(value, this.$t('range.edit_success'))
                break
                case 'Status':
                    message = start.concat(value, this.$t('range.status_success'))
                break
                case 'Assign':
                    message = start.concat(value, this.$t('range.assign_success')) 
                break
            }
            return message
        },
        handleNotification(title, dynamicVariant, message) {
            this.$notify({
                title: dynamicVariant.toUpperCase(),
                message: message,
                type: dynamicVariant,
                offset: 100
            });
        },
        changeTitleStatus(data) {
            return this.$t('range.status_type.' + data.status)
        },
        countDownChanged(dismissCountDown) {
            this.alert.dismissCountDown = dismissCountDown;
        },
        changeAction(data) {
            return this.$t('range.action_type.' + data.status)
        },
        changeColorType(data) {
            return (data.status === 0 ? 'success' : 'info')
        },
        changeStatus(data) {
            return this.$t('range.status_type.' + data) 
        },
        handleTabClick(e) {
            this.details.type = e.name
            this.activeTab = this.tabs.find(tab => tab.title === e.name).value
            this.activeTabTitle = this.tabs.find(tab => tab.title === e.name).title
            
            this.getRange()
        },
        reset() {
            this.q = { card_code: null, range_code: null, $size: 30, $page: 1 }
            this.getRange()
        },
        search() {
            this.getRange()
        },
        getRange() {
            if (this.q.card_code === null) {
                delete this.q.card_code
            }

            if(this.q.range_code === null){
                delete this.q.range_code
            }

            let params = Object.assign({
                $orderby: '-id',
                type: this.activeTab
            }, this.q)
            
            this.queryParam = encodeQueryData(params)
            this.getRangeList(this.queryParam)
            this.getList()
        },
        getList() {
            this.rangeData = this.range
        },
        getOrder() {
            this.orderData = this.orderList
        },
        handleSizeChange (val) {
            this.q.$size = val
            this.getRange()
        },
        handleCurrentChange (val) {
            this.q.$page = val
            this.getRange()
        },
        filterDetails(item, range, type) {
            return {
                item: item,
                filterCards: findstrict(range.list, 'type', type),
                filtercompanies: findstrict(range, 'type', type)
            }
        }, 
        concat(strStart, strEnd) {
            return (strStart + ' ' + strEnd)
        },
        executeOrder(flag, card) {
            let param = Object.assign({card: card})
            if (flag === 0) {
                this.getOrderDeposit(encodeQueryData(param))
            }else {
                this.getOrderWithdraw(encodeQueryData(param))
            }
        }
    },
    computed: {
        ...mapState(
            {
                cards: state => state.common.cards,
                rangeCode: state => state.common.rangeCode,
                companies: state => state.common.companies,
                order: state => state.common.order,
                orderList: state => state.common.orderList,
                range: state => state.range.range
            }
        )
    },
    watch: {
        range: function() {
            this.getList()
        },
        order: function() {
            // this.executeOrder(this.activeTab, this.cardData)
            this.getOrder()
        }
    },
    created() {
        this.getCards()
        this.getCompanies()
        this.getRangeCode()
        this.getRange()
    }
}

export const enRange = {
    //General
    all: 'All',
    name: ' Range',
    range_char: 'Range Code: ',
    add_success: 'New range was successfully added',
    edit_success: ' was successfully updated',
    status_success: ' was changed the status to ',
    assign_success: ' was successfully assigned a card code/company',
    update_range: 'Update Range ',
    tab_type: {
        0: 'Collection',
        1: 'Payment'
    },

    //Table
    range_code: 'Range Code',
    range: 'Range',
    cards: 'Cards',
    companies: 'Companies',
    status: 'Status',
    update_at: 'Update Time',
    action: 'Actions',

    // Action Link and Buttons
    search: 'Search',
    reset: 'Reset',
    add: 'Add',
    edit: 'Edit',
    view: 'View',
    assign: 'Assign',
    action_type: {
        0: 'Enable',
        1: 'Disable'
    },
    status_type: {
        0: 'Inactive',
        1: 'Active'
    }
}

export const zhRange = {
    //General
    all: '所有',
    name: ' 范围',
    range_char: '范围代码: ',
    add_success: '新范围已成功添加',
    edit_succes: ' 已成功更新',
    status_success: ' 被改为状态 ',
    assign_success: ' 成功分配了一个卡代码/公司',
    update_range: '更新范围 ',
    tab_type: {
        0: '采集',
        1: '付款'
    },

    //Table
    range_code: '范围代码',
    range: '范围',
    cards: '牌',
    companies: '公司',
    status: '状态',
    update_at: '更新时间',
    action: '操作',

    // Action Link and Buttons
    search: '查询',
    reset: '重置',
    add: '加',
    edit: '编辑',
    view: '视图',
    assign: '分配',
    action_type: {
        0: '启用',
        1: '禁用'
    },
    status_type: {
        0: '禁用',
        1: '启用'
    }
}
</script>
